import React, {useEffect, useState} from 'react';
import { Form, Button ,Input,Modal,Row,Col,message,Upload} from 'antd';
import { connect } from 'umi';
const FormItem = Form.Item;
import { validateBankNo } from '@/utils/utils';
import { UploadOutlined } from '@ant-design/icons';
import {getUploadUrl} from "@/utils/upload";
import store from 'store2';

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

const AddForm = (props) => {
  const { onSubmit, onCancel,record, loading,visible,currentUser} = props;
  const [form] = Form.useForm();
  const [title,setTitle] = useState(null);
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [data,setData] = useState([]);

  useEffect(() => {
    if(currentUser){
      const fieldsValue = store(`personnel-bankcard-` + currentUser.id);
      if(fieldsValue){
        let idcardDownUrl = fieldsValue.idcardDownUrl?.file ? fieldsValue.idcardDownUrl?.file.response : fieldsValue.idcardDownUrl;
        let idcardUpUrl = fieldsValue.idcardUpUrl?.file  ? fieldsValue.idcardUpUrl?.file.response : fieldsValue.idcardUpUrl;
        form.setFieldsValue({...fieldsValue,idcardDownUrl:idcardDownUrl,idcardUpUrl:idcardUpUrl});
        setFileUploadUrls([idcardUpUrl,idcardDownUrl]);
        setData({
          idcardUpUrl: idcardUpUrl ? [{
            uid: 'idcardUpUrl1',
            name: idcardUpUrl.split('----')[1],
            status: 'done',
            url: idcardUpUrl,
          }] : null,
          idcardDownUrl: idcardDownUrl ? [{
            uid: 'idcardUpUrl2',
            name: idcardDownUrl.split('----')[1],
            status: 'done',
            url: idcardDownUrl,
          }] : null
        })
      }else {
        form.setFieldsValue(currentUser);
        if (record) {
          setTitle("编辑银行卡");
          form.setFieldsValue(record);
          setData({
            idcardUpUrl: record.idcardUpUrl ? [{
              uid: 'idcardUpUrl1',
              name: record.idcardUpUrl.split('----')[1],
              status: 'done',
              url: record.idcardUpUrl,
            }] : null,
            idcardDownUrl: record.idcardDownUrl ? [{
              uid: 'idcardUpUrl2',
              name: record.idcardDownUrl.split('----')[1],
              status: 'done',
              url: record.idcardDownUrl,
            }] : null
          })
        } else {
          setTitle("新增银行卡")
        }
      }
    }
  }, [visible]);

  const fileList =(urlKey) =>({
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: data[urlKey],
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let index = data[urlKey].indexOf(info.response);
      if (index > -1) {
        data[urlKey].splice(index, 1);
      }
    }
  });

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
    setFileUploadUrls([]);
    setData([]);
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields()
    if(!validateBankNo(fieldsValue.bankcardNum)){
       return  message.error("银行卡格式错误，请先核实！")
    }
    form.resetFields();
    onSubmit({
      ...fieldsValue,oid:currentUser.id.toString(),
      id:record && record.id,
      idcardUpUrl:fileUploadUrls[0],
      idcardDownUrl:fileUploadUrls[1]
    });
    setFileUploadUrls([]);
    setData([]);
  };

  const onFormSave = async () => {
    const fieldsValue = await form.validateFields();
    store(`personnel-bankcard-` + currentUser.id,fieldsValue);
    message.success("信息暂存成功！");
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="持卡人姓名">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="bankcardNum" label="银行卡号" rules={[{required: true, message: '银行卡号不能为空'}]}>
              <Input/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="bankAccount" label="开户银行" rules={[{required: true, message: '开户银行不能为空'}]}>
              <Input/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="subBranch" label="所属支行" rules={[{required: true, message: '所属支行不能为空'}]}>
              <Input/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="idcardUpUrl" label="银行卡正面" rules={[{required: true, message: '银行卡正面不能为空'}]}>
              <Upload {...fileList('idcardUpUrl')}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="idcardDownUrl" label="银行卡反面" rules={[{required: true, message: '银行卡反面不能为空'}]}>
              <Upload {...fileList('idcardDownUrl')}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button onClick={() => onFormSave()}>暂存</Button>
        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  }

  return (
    <Modal
      maskClosable={false}
      width={1280}
      destroyOnClose
      centered
      title={title}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(AddForm)
